# 高危评分相关接口
import logging
import time

from flask_restful import Resource
from flask import jsonify, request

from command.handler.dict_handler import get_dict_value
from event import event_type
from utility.api_security import APISecurity
from utility.message_manager import MessageBusManager
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility import tools
class HighRiskScoreInsert(Resource):
    """
        新增高危评分
        data(json):
            gwpfIds 高危评分选项id数组
            archivesId 档案Id
    """
    def post (self):
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})
            params = tools.get_params(request)
            # 参数校验
            req_params = ['gwpfIds','archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            odoo = OdooManager().get_instance()
            gwpfIds = params.get('gwpfIds')
            gwpfs = odoo.env['dict.gwpf'].search_read([('id', 'in', gwpfIds)])
            total = 0
            for gwpf_item in gwpfs:
                total += gwpf_item['score']
            insert_data = {
                "total": total,
                "gwpf_ids": tools.parse_M2M_params(params.get('gwpfIds')),
                "pg_jg": 1,
                "pg_sj": time.strftime("%Y-%m-%d",time.localtime()),
                "pg_ys": payload['aud'],
                'archives_id': params.get('archivesId')
            }
            main_id = odoo.env['risk.score.record'].create(insert_data)
            create_event = event_type.OperationLogEvent('新增高危评分', '档案id:{}, 高危评分id:{}'.format(params.get('archives_id'), main_id))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            odoo.env['res.archives'].write(params.get('archivesId'), {
                'gwpf_ids': tools.parse_M2M_params(params.get('gwpfIds'))
            })
            create_event = event_type.OperationLogEvent('修改档案信息','档案id:{}'.format(params.get('archives_id')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            insert_data['id'] = main_id
            insert_data['gwpfIds'] = params.get('gwpfIds')
            return jsonify({
                "msg": "success",
                "code": 0,
                "data": insert_data
            })
        except Exception as e:
            logging.exception(e)
            jsonify({
                'msg': error_code[100],
                'code': 100
            })

class HighriskScoreUpdateAPI(Resource):
    """
        修改高危评分
        data(json)
            id 记录Id
            archivesId 档案Id
            gwpfIds 高危评分选项id数组
    """
    def put(self):
        try:
            # token校验
            payload = APISecurity().verify_access_token()
            if not payload:
                return jsonify({'code': 901, 'msg': error_code[901]})
            params = request.json
            # 参数校验
            req_params = ['gwpfIds','archivesId', 'id']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            odoo = OdooManager().get_instance()
            gwpfIds = params.get('gwpfIds')
            gwpfs = odoo.env['dict.gwpf'].search_read([('id', 'in', gwpfIds)])
            total = 0
            for gwpf_item in gwpfs:
                total += gwpf_item['score']
            update_data = {
                'total': total,
                "gwpf_ids": [(6, 0, params.get('gwpfIds'))],
                "pg_jg": 1,
                "pg_sj": time.strftime("%Y-%m-%d", time.localtime()),
                "pg_ys": payload['aud'],
                'archives_id': params.get('archivesId')
            }
            odoo.env['risk.score.record'].write(params.get('id'), update_data)
            create_event = event_type.OperationLogEvent('修改高危评分', '档案id:{}, 高危评分id:{}'.format(params.get('archives_id'), params.get('id')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            odoo.env['res.archives'].write(params.get('archivesId'), {
                'gwpf_ids': [(6, 0, params.get('gwpfIds'))]
            })
            create_event = event_type.OperationLogEvent('修改档案信息','档案id:{}'.format(params.get('archives_id')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件

            update_data['gwpfIds'] = params.get('gwpfIds')
            return jsonify({
                'code': 0,
                'msg': '修改成功',
                'data': update_data
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({
                "msg": error_code[100],
                'code': 100
            })

class HighriskScoreQueryAPI(Resource):
    """
        回显高危评分
        params:
            archivesId 档案Id
    """
    def get(self):
        try:
            params = request.values
            # 参数校验
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            odoo = OdooManager().get_instance()
            # 获取该档案下最新的信息
            res = odoo.env['risk.score.record'].search_read([('archives_id', '=', int(params.get('archivesId')))], ['gwpf_ids', 'total', 'pg_sj', 'pg_ys', 'pg_jg', 'id', 'total'])
            if (res):
                res = res.pop()
                data = {
                    'pgJgName': res['pg_jg'][1] if res['pg_jg'] else None,
                    'pgYsName': res['pg_ys'][1] if res['pg_ys'] else None,
                    'pgSj': res['pg_sj'],
                    'gwpf': [],
                    'id': res['id'],
                    'total': res['total']
                }
                gwpf_ids = res['gwpf_ids']
                if gwpf_ids:
                    gwpf_dict = odoo.env['dict.gwpf'].search_read([('id', 'in', gwpf_ids)], ['id', 'score', 'code', 'name', 'type'])
                    for gwpf_dict_item in gwpf_dict:
                        fa_dict =  get_dict_value(gwpf_dict_item['type'], 'ck_gwpf_type')
                        data_item = {
                            'gwpfysTypeCode': gwpf_dict_item['type'],
                            'gwpfysTypeName': fa_dict,
                            'gwpfysCode': gwpf_dict_item['code'],
                            'gwpfysName': gwpf_dict_item['name'],
                            'gwpfysFz': gwpf_dict_item['score'],
                            'id': gwpf_dict_item['id']
                        }
                        data['gwpf'].append(data_item)
                res = data
            else:
                res = None
            return jsonify({
                'code': 0,
                'msg': 'success',
                'data': res
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({
                'msg': error_code[100],
                'code': 100
            })

class HighriskScoreFactorsListAPI(Resource):
    """
        获取高危评分右侧内容
        params:
            gwpfysTypeCode 类型code
            searchText 关键字
    """
    def get(self):
        try:
            params = request.values
            query = []
            if (params.get('searchText')):
                query.append(('name', 'like', params.get('searchText')))
            if (params.get('gwpfysTypeCode')):
                query.append(('type', '=', params.get('gwpfysTypeCode')))
            odoo = OdooManager().get_instance()
            list = odoo.env['dict.gwpf'].search_read(query, [
                'name', 'score', 'type', 'id', 'code'
            ])
            res_list = []
            for list_item in list:
                fa_dict = get_dict_value(list_item['type'], 'ck_gwpf_type')
                item = {
                    'gwpfysTypeCode': list_item['type'],
                    'gwpfysTypeName': fa_dict,
                    'gwpfysCode': list_item['code'],
                    'gwpfysName': list_item['name'],
                    'gwpfysFz': list_item['score'],
                    'id': list_item['id']
                }
                res_list.append(item)
            return jsonify({
                'msg': 'success',
                'code': 0,
                'data': res_list
            })
        except Exception as e:
            logging.exception(e)
            return jsonify({
                'msg': error_code[100],
                'code': 100
            })